import { defineComponent, ref, watchEffect } from 'vue'
import { NUpload } from 'naive-ui'
import type { UploadFileInfo, UploadCustomRequestOptions } from 'naive-ui'
import systemApi from '@/service/api/system'

export default defineComponent({
  props: {
    modelValue: {
      type: String,
      default: () => ''
    }
  },
  emits: ['update:modelValue'],
  setup(props, { emit }) {
    const fileList = ref<UploadFileInfo[]>([])
    watchEffect(() => {
      if (props.modelValue && fileList.value.length === 0) {
        fileList.value = [
          {
            id: props.modelValue,
            name: props.modelValue,
            url: props.modelValue,
            thumbnailUrl: props.modelValue,
            status: 'finished'
          }
        ]
      }
    })
    const customRequest = (options: UploadCustomRequestOptions) => {
      const params: any = new FormData()
      params.append('file', options.file.file)
      systemApi.upload(params).then(({ data }) => {
        options.file.thumbnailUrl = data.url
        options.file.url = data.url
        options.onFinish()
      })
    }
    const handRemove = () => {
      emit('update:modelValue', '')
    }
    const finishChange = (e: any) => {
      emit('update:modelValue', e.file.url)
    }
    return () => (
      <>
        <NUpload
          accept='image/*'
          default-file-list={fileList.value}
          list-type='image-card'
          max={1}
          showPreviewButton
          customRequest={customRequest}
          onFinish={finishChange}
          onRemove={handRemove}
        />
      </>
    )
  }
})
